%% Start.m Remote SImulation Test Bench

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   Latest Change By: Etgar Israeli Tsiper
%   Latest Change Date: 28/05/13
%   What was changed: 
%      1. Defining a 'cosine' Type singal
%      2. First work on CalibrationFunction
%
%   Changes before By: Etgar Israeli
%   Latest Change Date: 20/05/13
%   What was changed: 
%   in ErrorCheck.m:
%      1. Trial of a new way to correlate between 2 signals - in Time Domain
%      2. Plotting resualt of 'sinc' to check reliability
%       * We need to check why the Ratio between time_axis is 5.71 and not
%       5 exactly. %%%%
%
%   Changes before By: Shahar Tsiper
%   Latest Change Date: 23/04/13
%   What was changed:   
%       changed algorithm to SBR4 and updated the value for m
%       Also changed output display and fixed relatively good mixing series
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Initializiation
close all; clear all ; %
addpath(genpath(pwd));

% dbstop in RecoverSignal;
%%  Iitialize the type and state of the random number generator to its startup 
%%  configuration
rng('default');
rng('shuffle');

%% Globals
global NumSamplesFactor;

global printArray;
printArray = setfield(printArray, 'signal', false); 

%% Define Signal Parameters
N = 6;                          % N equals twice the number of signal bands
B = 10.5e6 ;                   % Signal BW
fmax = 2.4608e+09;  %maximal freqquency

% Select signal modulation type:
% sinc, bpsk or qpsk or cosine
Type = 'qpsk';         

% Select Noise Level
SNR  =10;

%% Define MWC Parameters
q=1;    %expanding factor, q can only be odd number

% Select Recovery Algorithm
% SBR  OPTINS ={ 'SBR4' , 'SBRspecial'}
SBR ='SBRSpecial';

% Select the Sequence Length/ if M=[], the Algorithm selects it
% automatically
M=255;

% Select folding resolution, fp>=BW is necessary. if fp=[], the Algorithm selects it
% automatically
fp=19.608e+06;

% Define Hardware Channels, if HardwareChannels=[],  the Algorithm selects it
% automatically
HardwareChannels  = 20; 

% determine the CTF frame length. The actual size that will be generated is 2*q*NumSamplesFactor. 
% Note that there is a delay because of the digital filters, and the actual length of
% the CTF frames in the simulation is shorter then 2*q*NumSamplesFactor
NumSamplesFactor = 100 ;  

% Generation of sequence

        %%% TEST LFSR SEQUENCE - UNMARK THIS CODE TO RETEST ALL LFSR
%         %% OPTIONS
%         [SeqDic, LFSR_IC] = generateLFSR_Seuence(   );
%         C=nchoosek(1:6,4);
%         
%         %%%   LFSR SEQUENCE  - UNMARK THIS CODE WHEN LFSR SEQUENCE ALREADY
%         %%%   EXIST AND STORED AT LFSR_SEL_SEQ
%         opt=3; %decide which of the sequences stored  in LFSR_SEL_SEQ functio to use
%         SignPatternsMat = LFSR_SEL_SEQ(opt);
%         SignPatternsMat=SignPatternsMat(:,1:M);   %the last bis is excessive becaue the sequence is 255bit cyclic

        % %%% AUTO SEQUENCE  - UNMARK THIS SECTION IF YOU WANT TO GENERATE
        % A RANDOM SEQUENCE
        % SignPatternsMat=[]; 
        
      SignPatternsMat = ManualSequence( HardwareChannels , M );
%       SHAHAR - this make the same mixing series each time
%         good=load('Data/SignPatternMat-good-0305.mat');
%         SignPatternsMat = good.SignPatternsMat;
%         
%% START SIMULATION RUN
ResultsMat=[];
Result_Array={[]};

%% USE THIS FIELD TO OPTIMZIE DIFFERENT PARAMETRS. 
% The following code will test different qe.g. vecPar
% % % % vecPar=[1,3,5];
%%%%% 
% % % % for vecParCount=1:length(vecPar)
% % % % 
% % % %     q = vecPar(vecParCount);
% % % % 
% % % %     %% Constructing the signal
% % % %     SigStruct = ConstructSignalByParamters( N , B , fmax,Type, SNR,SBR  );
% % % %  
% % % %     %%% UNMARK IF RANDOM CARRIERS ARE REQUIRED
% % % %     SigStruct = setfield(SigStruct, 'Carriers', 'random'); 
% % % %  
% % % %     %%% UNMARK IF CARRIER ARE TO BE SPECIFIED
% % % %      SigStruct = setfield(SigStruct, 'Carriers', 'specify'); 
% % % %      carriers=[1.5*fp, 5.5*fp, 20.5*fp];
% % % %      SigStruct = setfield(SigStruct,'CarrierString',num2str(carriers)); 
% % % %     
% % % %     %% Define MWC Settings
% % % %      MWCStruct = Set_MWC(SigStruct,SignPatternsMat, q,SBR,fp,M);
% % % % 
% % % %     %% Call for Simulation
% % % %     tic
% % % %     for rm=1:100
% % % %         Success= mwcSimulator( SigStruct,MWCStruct,SNR);
% % % %         ResultsMat(vecParCount,rm,:)=reshape(Success,[1,1,length(Success)]);
% % % %     end
% % % %     toc
% % % %     
% % % % end

vecPar= [100]; %use here the values to be compared over the simulation

for vecParCount=1:length(vecPar)

    NumSamplesFactor = vecPar(vecParCount);  %Updating simulation parametrs

    %% Constructing the signal
    SigStruct = ConstructSignalByParamters( N , B , fmax,Type, SNR,SBR  );
 
    %%% UNMARK TO FORCE RANDOM CARRIERS 
    %     SigStruct = setfield(SigStruct, 'Carriers', 'random'); 
 
%     %%% UNMARK IF CARRIER ARE TO BE SPECIFIED
     SigStruct = setfield(SigStruct, 'Carriers', 'specify'); 
     carriers=[30*fp, 40*fp, 80*fp];
     SigStruct = setfield(SigStruct,'CarrierString',num2str(carriers)); 

    %% Define MWC Settings
     MWCStruct = Set_MWC(SigStruct,SignPatternsMat, q,SBR,fp,M,HardwareChannels);

    %% Calculating recovery rate by numerous simulation
    for rm=1:1
        [Success, CurRunDB,Original_Signal_Time_axit, Original_Signal] = mwcSimulator( SigStruct,MWCStruct,SNR);
        ResultsMat(vecParCount,rm,:)=reshape(Success,[1,1,length(Success)]);
    end
end
%% display recovery signal
f_rec = 1/(CurRunDB.RecTimeAxis(2)-CurRunDB.RecTimeAxis(1));
% figure;
% % hold on;
% hold off;
% figure;
Tanalog_Original = Original_Signal_Time_axit(2)- Original_Signal_Time_axit(1);% Sample time
OrigTimeAxis=Original_Signal_Time_axit;
% display_at_freq_domain( 1/Tanalog_Original,Original_Signal,fmax,'Original - blue *, Recovery - red','','b*');
% figure;
% 
% display_at_freq_domain( f_rec,CurRunDB.RecSignal,fmax,'Original - blue *, Recovery - red','','r');

%% Error Check in time and freq domain:
H2=0;
ErrorCheck(Original_Signal,Tanalog_Original,real(CurRunDB.RecSignal),1/f_rec,fmax,OrigTimeAxis,SNR,Type,H2);

%% Compure Average Recovery Rate
RecoveryRate_temp = mean(ResultsMat,2);
RecoveryRate = 100*squeeze(RecoveryRate_temp)';

% Save Results
% save('FinalSettings_Results');
